using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public enum HatLotteryRewardType
{
    Base = 1,               // 固定奖励组
    Normal = 2,             // 奖励池
    Force = 3               // 固定循环奖励池
}

public class UIHatLottery : UIBasePanel
{
    [SerializeField] Button m_openBtn;              // 打开界面按钮
    [SerializeField] Button m_closeBtn;             // 关闭界面按钮(临时, 后续可能需要删除)
    [SerializeField] Transform m_rewardsParent;     // 获得的奖励父节点
    [SerializeField] Button m_exitBtn;              // 中途退出按钮
    [SerializeField] Transform m_hatsParent;        // 帽子父节点
    [SerializeField] GameObject m_lose;             // 失败界面
    [SerializeField] Text m_totalRoundText;         // 总轮次
    [SerializeField] Text m_currentRoundText;       // 当前轮次
    [SerializeField] Button m_nextRoundBtn;         // 下一轮按钮(临时, 后续根据需求是否删除)


    // 所有的帽子
    List<UIHatLotteryItem> hatItemsList = new List<UIHatLotteryItem>();
    HashSet<int[]> rewardHatHash = new HashSet<int[]>();    // 帽子奖励内容
    List<int[]> rewardGetList = new List<int[]>();          // 已获得的奖励列表
    List<int[]> rewardRandomList = new List<int[]>();       // 可随机到的奖励池
    bool isWinning;                                         // 是否中奖
    int rewardCount;                                        // 奖励个数
    int rewardRandomCount;                                  // 可随机奖励池总数
    int totalRound;                                         // 总轮次
    int currentRound;                                       // 当前轮次
    int roundID;                                            // 当前轮次对应奖励ID
    int rewardRateIndex;                                    // 中奖概率下标
    int rewardRateLength;                                   // 中奖概率个数
    int diamondContinueIndex;                               // 继续挑战消耗钻石数量下标
    int diamondContinueLength;                              // 继续挑战消耗钻石数量个数
    int diamondRestartIndex;                                // 重新挑战消耗钻石数量下标
    int diamondRestartLength;                               // 重新挑战消耗钻石数量个数
    int baseCount;                                          // 固定奖励组占据个数
    int rewardLossMultiple;                                 // 失败扣除奖励倍数
    int continueADRound;                                    // 看视频继续挑战最高轮次

    private void Start()
    {
        GetHatItems();
        roundID = GameConsts.HatLotteryFitstID;
        rewardRateIndex = 0;
        rewardRateLength = GameConsts.HatLotteryRewardRate.Count;
        diamondContinueIndex = 0;
        diamondContinueLength = GameConsts.HatLotteryContinueDiamond.Count;
        diamondRestartIndex = 0;
        diamondRestartLength = GameConsts.HatLotteryRestartDiamond.Count;
        baseCount = GameConsts.HatLotteryBaseCount;
        continueADRound = GameConsts.HatLotteryContinueADRound;
        rewardLossMultiple = GameConsts.HatLotteryFailLossMultiple;

        m_openBtn.onClick.AddListener(BeginHat);
        m_closeBtn.onClick.AddListener(CloseBtnClicked);
        m_nextRoundBtn.onClick.AddListener(NextRound);
        m_nextRoundBtn.gameObject.SetActive(false);

        LoadRewardData();

        Events();
    }

    /// <summary>
    /// 开启活动
    /// </summary>
    private void BeginHat()
    {
        currentRound = 1;
        roundID = GameConsts.HatLotteryFitstID;
        m_currentRoundText.text = currentRound.ToString();
        Show();
    }

    /// <summary>
    /// 关闭界面
    /// </summary>
    private void CloseBtnClicked()
    {
        Hide();
    }

    void Events()
    {
        EventManager.Instance.AddListener(EEventType.Logic_HatLottery_ClickHat, ClickHat);
    }

    void LoadRewardData()
    {
        foreach (var item in DICT_HATLOTTERY_REWARD.Para.Values)
        {
            if (item.REWARD_TYPE != (int)HatLotteryRewardType.Force)
            {
                rewardRandomList.Add(item.REWARD_ITEMS);
            }
        }
        rewardRandomCount = rewardRandomList.Count;
    }

    /// <summary>
    /// 获取帽子
    /// </summary>
    private void GetHatItems()
    {
        hatItemsList = m_hatsParent.GetComponentsInChildren<UIHatLotteryItem>().ToList();
        foreach (var item in hatItemsList)
        {
            item.HideReward();
        }
    }

    /// <summary>
    /// 点击帽子按钮
    /// </summary>
    /// <param name="evt"></param>
    /// <returns></returns>
    private bool ClickHat(IEvent evt)
    {
        Debug.Log($"UIHatLottery 点击帽子按钮");
        // 首先清空奖励内容
        rewardHatHash.Clear();
        // TODO: 根据概率计算是否中奖, 计算奖励内容
        HATLOTTERY_DATA data = DICT_HATLOTTERY.Para[roundID];
        // 中奖概率
        float rate;
        // 如果是新手轮或者奖励轮, 中奖概率为1
        if (data.ROOKITROUND == 1 || data.LUCKROUND == 1)
        {
            rate = 1;
            isWinning = true;
            Debug.Log($"新手轮或者奖励轮");
        }
        else
        {
            // 如果上次没有中奖, 此次必中
            if (!isWinning)
            {
                isWinning = true;
            }
            else
            {
                rate = GameConsts.HatLotteryRewardRate[rewardRateIndex];
                if (rewardRateIndex < rewardRateLength - 1)
                {
                    rewardRateIndex++;
                }
                float randomValue = UnityEngine.Random.value;
                isWinning = randomValue < rate;
                Debug.Log($"Random:{randomValue} < rate: {rate};");
            }

        }
        // 如果中奖
        if (isWinning)
        {
            HATLOTTERY_REWARD_DATA DataReward = null;
            int forceID = data.FORCEROUND_REWARD;
            if (forceID != 0)
            {
                DataReward = DICT_HATLOTTERY_REWARD.Para[forceID];
                rewardHatHash.Add(DataReward.REWARD_ITEMS);
            }
            // 获取奖励个数
            if (data.LUCKROUND == 1)
            {
                rewardCount = hatItemsList.Count;
            }
            else
            {
                rewardCount = hatItemsList.Count - 1;
            }
            Debug.Log($"rewardCount: {rewardCount}  rewarddHatHash: {rewardHatHash.Count} rewardRandomList: {rewardRandomList.Count}");
            // 计算具体奖励内容
            if (rewardCount - rewardHatHash.Count > rewardRandomList.Count)
            {
                Debug.LogWarning($"奖励池数量不足以填充奖励内容");
                return true;
            }
            else
            {
                int totalRewardCount = rewardRandomList.Count;
                while (rewardHatHash.Count < rewardCount)
                {
                    int randomIndex = UnityEngine.Random.Range(0, totalRewardCount);
                    int[] reward = rewardRandomList[randomIndex];
                    if (!rewardHatHash.Contains(reward))
                    {
                        rewardHatHash.Add(reward);
                    }
                }
            }
            roundID = data.NEXT_ID;
        }


        ShowHatRewards();



        return true;
    }

    /// <summary>
    /// 点击帽子之后没有中奖, 失败
    /// </summary>
    void FailClick()
    {
        Debug.Log($"没有中奖");

        // TODO: 弹出失败界面

    }

    /// <summary>
    /// 展示帽子对应的奖励
    /// </summary>
    void ShowHatRewards()
    {
        // 日志显示奖励内容
        StringBuilder ss1 = new StringBuilder();

        UIHatLotteryItem hatChoosed = null;
        // TODO: 选中的帽子展示奖励内容
        foreach (var item in hatItemsList)
        {
            if (item.isClicked)
            {
                item.isClicked = false;
                // 如果有中奖
                if (rewardHatHash.Count > 0)
                {
                    int[] rewardGet = rewardHatHash.First();
                    item.ShowReward(rewardGet);
                    ss1.Append(rewardGet[0] + " " + rewardGet[1] + ", ");
                    rewardHatHash.Remove(rewardGet);
                    hatChoosed = item;
                    break;
                }
                // 如果没有中奖, 失败
                else
                {
                    FailClick();

                    item.ShowReward(null);
                    return;
                }

            }
        }

        // 其余帽子展示奖励内容
        foreach (var item in hatItemsList)
        {
            if (item == hatChoosed) continue;
            if (rewardHatHash.Count > 0)
            {
                int[] rewardShow = rewardHatHash.First();
                item.ShowReward(rewardShow);
                ss1.Append(rewardShow[0] + " " + rewardShow[1] + ", ");
                rewardHatHash.Remove(rewardShow);
            }
            else
            {
                item.ShowReward(null);
            }
        }

        Debug.Log($"第 {currentRound} 轮奖励内容: {ss1.ToString()}");
        m_nextRoundBtn.gameObject.SetActive(true);
    }

    /// <summary>
    /// 下一轮
    /// </summary>
    void NextRound()
    {
        foreach (var item in hatItemsList)
        {
            item.HideReward();
        }
        currentRound++;
        m_currentRoundText.text = currentRound.ToString();
        m_nextRoundBtn.gameObject.SetActive(false);
    }
}
